import { Component, ViewChild, Host, ChangeDetectorRef } from '@angular/core';
import { AppComponent } from '../../../app.component';
import { environment } from '../../../../environments/environment';
import { UtilsService } from '../../../shared/services/utils.service';
import { ResearchProductInvolvementService } from './researchProductInvolvement.service';
import { Subscription } from 'rxjs/Subscription';
import { ColumnOptions } from '../../../shared/components/table/models/columnOptions.model';
import { PaginationPositionDisplayEnum, TableComponent } from '../../../shared/components/table/table.component';
import { TableRouterLink } from '../../../shared/components/table/models/tableRouterLink.model';
import { TableOptions } from '../../../shared/components/table/models/tableOptions.model';
import { StorageService } from '../../../shared/services/storage.service';
import { ProductInvolvementFilterModel } from './models/productInvolvementFilter.model';
import { AnalyticsService } from '../../../shared/services/googleAnalytics.service';
import { GoogleAnalyticsBeacon } from '../../../shared/models/googleAnalytics.model';
import { BaseComponent } from '../../../shared/components/baseComponent/base.component';
import { Observable } from 'rxjs';
import { FilterSettingModel } from '../../../shared/components/landing-page-filter/models/filterSetting.model';
import { FilterSettingOptionModel } from '../../../shared/components/landing-page-filter/models/filterSettingOption.model';
import { RangeOwnershipModel } from '../../../shared/models/rangeOwnership.model';


/**
 * Overall Product Involvement main component
 *
 * Author: Andrei Istrate
 * Date: 09.05.2018
 */

@Component({
    moduleId: module.id,
    templateUrl: 'researchProductInvolvement.component.html',
    styleUrls: ['../research.component.scss'],
    providers: [UtilsService, ResearchProductInvolvementService]
})
export class ResearchProductInvolvementComponent extends BaseComponent {
    constructor(@Host() private rootComponent: AppComponent,
        private productInvolvementService: ResearchProductInvolvementService,
        private analyticsService: AnalyticsService,
        private cdRef: ChangeDetectorRef
    ) {
        super(cdRef);
     }

    public readonly resourcesUrl: string = environment.resourcesUrl;

    public sub: Subscription;
    public assessmentsList: any[];
    public columns: ColumnOptions[];
    public subIndustryList: any[];
    public productInvolvementIndicators: any[];
    public source: any[];
    public elementCount: number;
    public filter: ProductInvolvementFilterModel = new ProductInvolvementFilterModel();
    public paginationPosition = PaginationPositionDisplayEnum.UpAndDown;
    public accountId: string = StorageService.get().userInfo.accountId;
    public settings: FilterSettingModel[] = [];
    
    private rangeOwnership: RangeOwnershipModel[] = [
        new RangeOwnershipModel("N/A", "N/A"),
        new RangeOwnershipModel("50-100%", "50-100%"),
        new RangeOwnershipModel("25-49.9%", "25-49.9%"),        
        new RangeOwnershipModel("10-24.9%", "10-24.9%"),
        new RangeOwnershipModel("5-9.9%", "5-9.9%"),
        new RangeOwnershipModel("0-4.9%", "0-4.9%")
    ];
    private landingFilter: any;

    @ViewChild('table') table: TableComponent;

    ngOnInit() {
        this.analyticsService.sendBeacon(new GoogleAnalyticsBeacon('Product Involvement Landing Page', 'Landing Pages', {}));
        this.source = [];
        if(!this.productPermissions.productinvolvement) 
        {
            this.rootComponent.finishLoading();
            return;
        }
        this.setColumns();
        
        Observable.forkJoin(
            this.productInvolvementService.getIndicatorsList(), 
            this.productInvolvementService.getIndustriesList()).subscribe(data=>{
                this.settings.push(new FilterSettingModel('indicators', 
                    (data[0] as any[]).map((element, index) => { return new FilterSettingOptionModel(element.symbol, element.name, 'indicators', index) }),
                    'Product Involvement Indicator',
                    'col-md-3',
                    (data[0] as any[]).length
                ));
    
                this.settings.push(new FilterSettingModel('subindustries', 
                    (data[1]  as any[]).map((element, index)  => { return new FilterSettingOptionModel(element.id, element.name, 'subindustries', index) }),
                    'Industry',
                    'col-md-4',
                    (data[1] as any[]).length
                ));
                
                this.settings.push(new FilterSettingModel('rangeOwnerships', 
                    this.rangeOwnership.map((element, index)  => { return new FilterSettingOptionModel(element.id, element.name, 'rangeOwnerships', index) }),
                    'Range/Ownership',
                    'col-md-2'
                ));
            });
            

        this.getBulkCompanies(new TableOptions("CompanyNameLowerCase"));
        
    }

    private setColumns() {
        this.columns = [
            new ColumnOptions('CompanyNameLowerCase', 'CompanyNameLowerCase', 'Company Names', 'col-md-2', true, false, false, undefined, false, true, false),
            new ColumnOptions('exchange', 'exchange', 'Exchange', 'col-md-1', false, false, false, undefined, false, false, false,true, undefined, false, false, true),
            new ColumnOptions('ticker', 'ticker', 'Ticker', 'col-md-1', false, false, false, undefined, false, false, false,true, undefined, false, false, true),
            new ColumnOptions('areaOfInvolvement', 'areaOfInvolvement', 'Area of Involvement', 'col-md-4', false, false, false, undefined, false, false, false, true, undefined, false, false, true, true),
            new ColumnOptions('rangeOwnership', 'rangeOwnership', 'Level of Involvement', 'col-md-2', false, false, false, undefined, false, false, false, true, undefined, false, false, true, true),
            new ColumnOptions('industry', 'industry', 'Subindustry', 'col-md-2', false, false, false, this.subIndustryList, true, false, false, true, undefined, false, false, true),
        ];
    }

    private getBulkCompanies(tableOptions: TableOptions): void {
        // this.filter.piIndicatorSymbolsStrFilter = UtilsService.arrayToStringWithPipes(this.filter.piIndicatorSymbolsStrFilter);
        // this.filter.piRangeOwnershipStrFilter = UtilsService.arrayToStringWithPipes(this.filter.piRangeOwnershipStrFilter);
        if (tableOptions.pageOptions.listOnly == false) {
            this.productInvolvementService.getCompaniesCount(tableOptions.filter, this.accountId).subscribe(data => {
                this.elementCount = data;
            });
        }

        this.productInvolvementService.getCompanies(tableOptions.filter, tableOptions.pageOptions.skip, tableOptions.pageOptions.take, tableOptions.orderByCol, tableOptions.orderByAsc, this.accountId).subscribe(data => {
            if (tableOptions.pageOptions.listOnly == false) {
                this.table.ResetPaginationToFirstPage();
            }
            let valuesToDisplay: any[];
            valuesToDisplay = data.map(company => {
                let areaOfInvolvement = [];
                let rangeOwnership = [];
                company.indicators.forEach(ind => {
                    areaOfInvolvement.push( { bold: true, name: ind.name});
                    rangeOwnership.push('');
                    ind.categories.forEach(category => {
                        areaOfInvolvement.push( {indent: true, name: category.name} );
                        rangeOwnership.push(category.rangeOwnership)
                    });
                });
                return {
                    CompanyNameLowerCase: new TableRouterLink(company.companyName, true, company.companyNameSafeUrl, 'productInvolvement'),
                    exchange: company.exchange,
                    ticker: company.ticker,
                    ariaOfInvolvement: areaOfInvolvement,
                    rangeOwnership: rangeOwnership,
                    industry: company.industry
                };
            });
            this.source = valuesToDisplay;
        });

    }

    public tableOptionsChanged(tableOptions: TableOptions): void {        
        this.getBulkCompanies(this.updateTableOptions(this.landingFilter, tableOptions));
    }

    ngAfterViewInit() {
        this.rootComponent.finishLoading();
    }
    
    public applyFilter(data: any){
        this.landingFilter = data;

        let tableOptions = new TableOptions('CompanyNameLowerCase');
        tableOptions.filter = this.table.filter['companyName'] ? { companyName: this.table.filter['companyName'] } : this.table.filter;
        this.getBulkCompanies(this.updateTableOptions(data, tableOptions));
    }

    private updateTableOptions(landingFilter: any, tableOptions: TableOptions): TableOptions{
        if(landingFilter){
            Object.keys(landingFilter).forEach(key => {            
                tableOptions.filter[key] = landingFilter[key];
            });        
        }
        return tableOptions;
    }
    
}